package core

import (
	"openzbox.com/driver/conn/gpio"
	"openzbox.com/driver/conn/gpio/gpioreg"
	"openzbox.com/log"
	"strconv"
	"strings"
	"time"
)

var POWERGPIO gpio.PinIO //= nuc98x.PC13
var LED_FALT gpio.PinIO  //= nuc98x.PC13
var LED_ACT gpio.PinIO   //= nuc98x.PC13

type IOCtrl struct {
	Name string `json:"name"`
	Gpio string `json:"gpio"`
}

func (box *Mbox) InitIOCtrl() {
	for _, iogpio := range box.SysCtrl {
		if strings.EqualFold(iogpio.Name, "power_reboot") {
			POWERGPIO = gpioreg.ByName(iogpio.Gpio)
		} else if strings.EqualFold(iogpio.Name, "fault_led") {
			LED_FALT = gpioreg.ByName(iogpio.Gpio)
		} else if strings.EqualFold(iogpio.Name, "info_led") {
			LED_ACT = gpioreg.ByName(iogpio.Gpio)
		}
	}
	log.Debugf("SysCtrl:%v", box.SysCtrl)
	log.Debugf("LED_FALT gpio:%v", LED_FALT)
	log.Debugf("LED_ACT gpio:%v", LED_ACT)
	log.Debugf("Power gpio:%v", POWERGPIO)

}

func blinkFault(args ...interface{}) {
	//log.Infof( "%v",LED_ACT)
	//LEDRED :=0x00 + 13 + 32
	speed, _ := strconv.Atoi(args[0].([]interface{})[0].(string))
	//sysfs.Pins[LEDRED].Out(gpio.High)
	LED_FALT.Out(gpio.Low)
	//log.Infof("LED_FALT %v",LED_FALT.Read())
	time.Sleep(time.Millisecond * (time.Duration(speed)))
	//sysfs.Pins[LEDRED].Out(gpio.Low)
	LED_FALT.Out(gpio.High)
	//log.Infof("LED_FALT %v",LED_FALT.Read())
	time.Sleep(time.Millisecond * (time.Duration(speed)))
}

func blinkAct(args ...interface{}) {
	//log.Infof( "%v",LED_ACT)
	//LEDRED :=0x00 + 11 + 64
	speed, _ := strconv.Atoi(args[0].([]interface{})[0].(string))
	//sysfs.Pins[LEDRED].Out(gpio.High)
	LED_ACT.Out(gpio.Low)
	//log.Infof("LED_ACT %v",LED_ACT.Read())
	time.Sleep(time.Millisecond * (time.Duration(speed)))
	//sysfs.Pins[LEDRED].Out(gpio.Low)
	LED_ACT.Out(gpio.High)
	//log.Infof("LED_ACT %v",LED_ACT.Read())
	time.Sleep(time.Millisecond * (time.Duration(speed)))
	//log.Infof("xxxxxxx")
}

func (box *Mbox) OpenFaultLED(speed int) {
	//speed, _:=  1000 //strconv.Atoi(args[0].([]interface{})[0].(string))
	box.gm.NewLoopGoroutine("blinkFault", blinkFault, strconv.Itoa(speed), "")
}
func (box *Mbox) CloseFaultLED() {
	box.gm.StopLoopGoroutine("blinkFault")
	LED_ACT.Out(gpio.Low)
}

func (box *Mbox) OpenActiveLED(speed int) {
	//speed, _:=  1000 //strconv.Atoi(args[0].([]interface{})[0].(string))
	box.gm.NewLoopGoroutine("blinkAct", blinkAct, strconv.Itoa(speed), "")
}
func (box *Mbox) CloseActiveLED() {
	box.gm.StopLoopGoroutine("blinkAct")
	LED_ACT.Out(gpio.Low)
}
